<template>
  <div class="app-container">
    <el-card class="filter-container" shadow="never">
      <div>
        <i class="el-icon-search"></i>
        <span>筛选搜索</span>
        <el-button style="float: right" @click="handleSearchList()" type="primary" size="small">查询结果</el-button>
        <el-button
          style="float: right;margin-right: 15px"
          @click="handleResetSearch()"
          size="small"
        >重置</el-button>
      </div>
      <div style="margin-top: 15px">
        <el-form :inline="true" :model="listQuery" size="small" label-width="140px">

          <el-form-item label="输入搜索：">
            <el-input style="width: 203px" v-model="listQuery.pname" placeholder="商品名称"></el-input>
          </el-form-item>

          <el-form-item label="上架状态：">
            <el-select v-model="listQuery.pon" placeholder="全部" >
              <el-option label="上架" value="1"></el-option>
              <el-option label="下架" value="0"></el-option>
            </el-select>
          </el-form-item>


          <el-form-item label="分类：">
            <el-select v-model="listQuery.ptid" placeholder="全部" >
              <el-option
                v-for="item in typeList"
                :key="item.ptid"
                :label="item.ptype"
                :value="item.ptid"
              ></el-option>
            </el-select>
          </el-form-item>

        </el-form>
      </div>
    </el-card>

    <el-card class="operate-container" shadow="never">
      <i class="el-icon-tickets"></i>
      <span>数据列表</span>

      <el-button class="btn-add" @click="handleAddProduct()" size="mini">添加</el-button>

      <el-button
        class="btn-add"
        :disabled="multipleSelection.length<1"
        size="mini"
        type="danger"
        @click="multiDelete()">
              批量删除
      </el-button>
    </el-card>

    <div class="table-container">
      <el-table
        ref="productTable"
        :data="list"
        style="width: 100%"
        @selection-change="handleSelectionChange"
        border
      >
        <el-table-column type="selection" width="60" align="center"></el-table-column>
        <el-table-column label="ID" width="100" align="center">
          <template slot-scope="scope">{{scope.row.pid}}</template>
        </el-table-column>

        
        <el-table-column label="商品名称" width="200" align="center">
          <template slot-scope="scope">
            <!-- <p>{{scope.row.pname}}</p> -->
            <el-input v-model="scope.row.pname" :disabled="scope.row.editShow"></el-input>
            <!-- <p>品牌：{{scope.row.brandName}}</p> -->
          </template>
        </el-table-column>

       
        <el-table-column label="简介" align="center">
          <template slot-scope="scope">
            <el-input v-model="scope.row.pinfo" :disabled="scope.row.editShow"></el-input>
          </template>
        </el-table-column>

        <el-table-column label="详细介绍" align="center">
          <template slot-scope="scope">
            <el-input v-model="scope.row.pdetnil" :disabled="scope.row.editShow"></el-input>
          </template>
        </el-table-column>

        <el-table-column label="库存" width="100" align="center">
          <template slot-scope="scope">
            <el-input v-model="scope.row.pamount" :disabled="scope.row.editShow"></el-input>
            <!-- <el-button type="primary" icon="el-icon-edit" @click="handleShowSkuEditDialog(scope.$index, scope.row)" circle></el-button> -->
          </template>
        </el-table-column>

        <el-table-column label="销量" width="100" align="center">
          <template slot-scope="scope">
            <el-input v-model="scope.row.salvolu" :disabled="scope.row.editShow"></el-input>
          </template>
        </el-table-column>

        <el-table-column label="上架状态" width="160" align="center">
          <template slot-scope="scope">
            <!-- <p
              :style="scope.row.pon?'color:green;':'color:red;'"
            >{{scope.row.pon | verifyStatusFilter}}
            
            </p> -->
             <el-switch
                @change="editProduct(scope.row)"
                :active-value="1"
                active-text="在线"
                :inactive-value="0"
                inactive-text="下架"
                v-model="scope.row.pon">
              </el-switch>
            <!-- <p>
              <el-button
                type="text"
                @click="handleShowVerifyDetail(scope.$index, scope.row)">审核详情
              </el-button>
            </p>-->
          </template>
        </el-table-column>
<!-- imgUrl+'/image/'+ -->
        <el-table-column label="商品图片" width="180" align="center">
          <template slot-scope="scope">
            <img
              style="width: 160px"
              :src="scope.row.productimages?imgUrl+'/image/'+ scope.row.productimages.piurl:''"
            />
          </template>
        </el-table-column>

        <el-table-column label="价格" width="120" align="center">
          <template slot-scope="scope">
            <p>￥{{scope.row.prices?scope.row.prices.price:'null'}}</p>
            <!-- <p>货号：{{scope.row.productSn}}</p> -->
          </template>
        </el-table-column>


        <el-table-column label="操作" width="160" align="center">
          <template slot-scope="scope">
            <p>
              <!-- <el-button
                size="mini"
                @click="handleShowProduct(scope.$index, scope.row)">查看
              </el-button>-->
              <el-button size="mini" @click="scope.row.editShow=false">编辑</el-button>

              <el-button
                size="mini"
                v-if="scope.row.editShow==false"
                @click="editProduct(scope.row)"
              >确定</el-button>
            </p>
            <p>
              <!-- <el-button
                size="mini"
                @click="handleShowLog(scope.$index, scope.row)">日志
              </el-button>-->
              <el-button size="mini" type="primary" @click="upImages(scope.$index, scope.row)">上传图片</el-button>
            </p>
            <p>
              <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>

            </p>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="batch-operate-container">
     

       <el-dialog
      title="上传商品图片"
      :visible.sync="dialogVisible"
      @close="dialogClose"
      width="50%">
      <el-form ref="productCate"  label-width="120px" >
       
  <!-- 图片 -->
        <el-form-item label="图标" prop="sname" >

            <el-upload
              action="/abc"
              list-type="picture-card"
              ref="upload"
              multiple
              :on-preview="handlePictureCardPreview"
              :on-change="handleChange"
              :auto-upload="false"
              :limit="limitCount"
              :on-exceed="handleExceed"
              :file-list="imgFile"
              :on-remove="handleRemove">
              <i class="el-icon-plus"></i>
            </el-upload>

            <el-dialog :visible.sync="dialogShow">
              <img width="100%" :src="dialogImageUrl" alt="">
            </el-dialog>

        </el-form-item>

  <!-- 图片完 -->
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleConfirm()" >确 定</el-button>
      </span>
    </el-dialog>


    </div>
    <div class="pagination-container">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        layout="total, sizes,prev, pager, next,jumper"
        :page-size="listQuery.pagesize"
        :page-sizes="[10,20,50]"
        :current-page.sync="listQuery.page"
        :total="total"
      ></el-pagination>
    </div>
    
  </div>
</template>
<script>
import {
  fetchList,
  // updateDeleteStatus,
  // updateNewStatus,
  // updateRecommendStatus,
  // updatePublishStatus
  updateProductImg,
  updateProduct,
  deleteProduct
} from "@/api/product";
import {fetchList as getTypeList}  from '@/api/productCate'
// import {fetchList as fetchSkuStockList,update as updateSkuStockList} from '@/api/skuStock'
// import {fetchList as fetchProductAttrList} from '@/api/productAttr'
// import {fetchList as fetchBrandList} from '@/api/brand'
// import {fetchListWithChildren} from '@/api/productCate'

const defaultListQuery = {
  // keyword: null,
  page: 1,
  pagesize: 10,
  pname:null,
  ptid:null,
  pon:null
};
export default {
  name: "productList",
  data() {
    return {
      imgUrl:'',
      updatePid:null,
        imgFile:[],
dialogVisible:false,
        isClientCertFile:true,
        dialogImageUrl:'',
        dialogShow: false,
        typeList:[],
      limitCount:5,
     
      listQuery: Object.assign({}, defaultListQuery),
      list: null,
      total: null,
      selectProductCateValue: null,
      multipleSelection: [],
      productCateOptions: [],
      brandOptions: [],
      publishStatusOptions: [
        {
          value: 1,
          label: "上架"
        },
        {
          value: 0,
          label: "下架"
        }
      ],
      verifyStatusOptions: [
        {
          value: 1,
          label: "审核通过"
        },
        {
          value: 0,
          label: "未审核"
        }
      ]
    };
  },
  created() {
      process.env.NODE_ENV === 'development' ? this.imgUrl = '/api/' : this.imgUrl = process.env.API_ROOT ;

    this.getList();
    this.getTypeData();
  },
  
  filters: {
    verifyStatusFilter(value) {
      if (value === 1) {
        return "在线";
      } else {
        return "下架";
      }
    }
  },
  methods: {
     // 新增or编辑点击确定
      handleConfirm(){
        let _this = this;
        this.$refs.upload.clearFiles();

        if (this.isClientCertFile) {
            this.$message.error("请选择图片")
            return
        }

          console.log(this.$refs.upload);
          // this.$refs.upload.submit();
          let param = new FormData(); // 创建form对象
          console.log(this.imgFile);
          param.append('pid',_this.updatePid);
          this.imgFile.forEach(msg => { 
              param.append('file', msg.raw, msg.raw.name); //此处一定是append file.raw 上传文件只需维护fileList file.raw.name要加上 
　　       }) 
          
              updateProductImg(param).then(res=>{
              _this.$message({
                  message: res.msg,
                  type: 'success',
                  duration:1000
                });
                _this.dialogVisible = false;
                _this.getList();
                
            })

      
      },
     // 预览图片
      handlePictureCardPreview(file) {
        // alert(file.url);
        this.dialogImageUrl = file.url;
        this.dialogShow = true;
      },
      upImages(index,row){
        // alert('asdf');
        this.updatePid =row.pid;
         this.dialogVisible = true;
      },
      // 下载图片
      handleDownload(file) {
        console.log(file);
      },
     //值改变 判读是否有值
      handleChange(file, fileList, name) {
        console.log(this.imgFile);
        this.hideUpload = fileList.length >= this.limitCount;
        // this.imgFile["file"] = fileList;
        let existFile = fileList.slice(0, fileList.length - 1).find(f => f.name === file.name)

      　　if (existFile) {
      　　　　this.$message.error('当前文件已经存在!');
      　　　　fileList.pop()
      　　}
      　　this.imgFile = fileList

        if (typeof this.imgFile != "undefined" && this.imgFile.length > 0) {
          this.isClientCertFile = false;
        } else {
          this.isClientCertFile = true;
        }
      },
      handleExceed(files, fileList) {
        this.$message.warning(
          '当前限制选择 5 个文件'
        );
      },
      //值被清空 
      handleRemove(file, fileList, name) {
        this.hideUpload = fileList.length >= this.limitCount;
        this.isClientCertFile = true;
      },
     dialogClose(){
        this.imgFile=[];
      },
      // 切换开关
    editProduct(row) {
      let { pid, pname, pinfo, pdetnil, pamount, salvolu, pon } = row;
      let data= { pid, pname, pinfo, pdetnil, pamount, salvolu, pon };
      console.log(data);

      updateProduct(data).then(res=>{
        console.log(res);
          this.getList();
      })
    },
    // handlePublishStatusChange(row) {
    //   let
    // },
    getProductSkuSp(row, index) {
      if (index === 0) {
        return row.sp1;
      } else if (index === 1) {
        return row.sp2;
      } else {
        return row.sp3;
      }
    },
    getList() {
      console.log(this.listQuery);
      fetchList(this.listQuery).then(response => {
        this.list = response.obj.list;
        this.list.map(msg => {
          this.$set(msg, "editShow", true);
        });
       

        console.log(this.list);
        this.total = response.obj.count;
      });
    },
    async getTypeData(){
      let res = await getTypeList({page:1,pagesize:12});
      this.typeList = res.obj.list;
      console.log(this.typeList);
    },
  
  
   
    
    handleSearchList() {
      this.listQuery.page = 1;
      this.getList();
    },
    // 跳转添加商品
    handleAddProduct() {
      this.$router.push({ path: "/pms/addProduct" });
    },
    handleSizeChange(val) {
      this.listQuery.page = 1;
      this.listQuery.pagesize = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.listQuery.page = val;
      this.getList();
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    
   
   
    handleResetSearch() {
      this.selectProductCateValue = [];
      this.listQuery = Object.assign({}, defaultListQuery);
    },
 // 批量删除商品
      multiDelete(){
        let list = this.multipleSelection;
        let data=list.map((res)=>{
          return res.pid
        })
        this.$confirm(`是否批量删除选中的${data.length}个商品`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteProduct({array:data}).then(response => {
            if(response.obj===0){
              this.$message({
                message: '部分商品有订单，不可删除',
                type: 'warning',
                duration: 1000
             });
            }
            if(response.stastus===200&&response.obj>0){
              this.$message({
                message: `成功删除${response.obj}个商品`,
                type: 'success',
                duration: 1000
              });
            }
           
            this.getList();
          });
        });
      },

   // 删除分类
      handleDelete(row) {
        this.$confirm('是否要删除该商品', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteProduct({array:[row.pid]}).then(response => {
             if(response.obj===0){
              this.$message({
                message: '部分商品有订单，不可删除',
                type: 'warning',
                duration: 1000
             });
            }
            if(response.stastus===200&&response.obj>0){
              this.$message({
                message: `成功删除${response.obj}个商品`,
                type: 'success',
                duration: 1000
              });
            }
           
            this.getList();
          });
        });
      },
   
  
    
  
   
    
   
    updateDeleteStatus(deleteStatus, ids) {
      let params = new URLSearchParams();
      params.append("ids", ids);
      params.append("deleteStatus", deleteStatus);
      updateDeleteStatus(params).then(response => {
        this.$message({
          message: "删除成功",
          type: "success",
          duration: 1000
        });
      });
      this.getList();
    }
  }
};
</script>
<style></style>


